require "Common/define"
require "Logic/Config"
require "Common/functions"

Item = {};
HelperFunc.SetUIEnv(Item)
local this = Item;

this.img_Quality = nil;
this.img_Frame = nil
this.img_Icon = nil;
this.stateCtrl = nil;
this.txt_Level = nil;
this.txt_refine = nil;
this.txt_num = nil;
this.maskCtrl = nil;
this.dialogCtrl = nil;
this.cornerMark = nil;
this.soulIcon = nil

function Item.Init()
    local name = getUIName(PanelNames.Item);
    panelMgr:ShowUI(name, this.onCreate, Config.useLocalUI);
end

function Item.onCreate(obj)
    obj:SetActive(false);
end
---@param obj GComponent
function Item.initData(obj, data, type, isBag, notShow,partnerId,notAddClick,isMultiple)
    img_Quality = obj:GetChild("quality");
    img_Frame = obj:GetChild("frame")
    img_Icon = obj:GetChild("icon");
    txt_num = obj:GetChild("num");
    this.name = obj:GetChild("name");
    txt_Level = obj:GetChild("level");
    txt_refine = obj:GetChild("refineLevel");
    cornerMark = obj:GetChild("cornerMark");
    local soulCtrl;
    if obj:GetChild("heroSoulmask") then
        this.soulIcon = obj:GetChild("heroSoulmask"):GetChild("icon")
        soulCtrl = obj:GetController("heroSoul")
    end
    --local ctrlRefineLevel = obj:GetController("refineLevel")
    --local ctrlRefineSlot = obj:GetController("refineSlot")
    local fontController = obj:GetController("font")
    this.showNameController = obj:GetController("isShowName");
    this.maskCtrl = obj:GetController("mask");
    this.dialogCtrl = obj:GetController("dialog");
    this.ifShowBar = obj:GetController("ifShowBar");
    this.ifMultipleCtrl = obj:GetController("ExtraReward");
    this.isShowRedDot = obj:GetController("isShowRedDot");
    this.invasionUpCtrl = obj:GetController("InvasionUp");
    local ctrlSuit = obj:GetController("suit")
    local iconDouble = obj:GetChild("iconDouble")
    stateCtrl = obj:GetController("state");
    local IsDoubleController = obj:GetController("IsDouble")
    local ctrl_time_box = obj:GetController("time-box")
    --if ctrlRefineLevel then
    --    ctrlRefineLevel.selectedIndex = 0
    --end
    if soulCtrl then
       soulCtrl.selectedIndex = 0
    end
    if this.isShowRedDot then
        this.isShowRedDot.selectedIndex = 0
    end
    if this.invasionUpCtrl then
        this.invasionUpCtrl.selectedIndex = 0
    end
    if ctrl_time_box then
        ctrl_time_box.selectedIndex = 0
    end
    if IsDoubleController then
        IsDoubleController.selectedIndex = 0
    end
    --iconSuit.url = ""
    local ctrlMirror = obj:GetController("heroMirror")
    local cornerMarkController = obj:GetController("cornerMark")
    if cornerMarkController then
        cornerMarkController.selectedIndex = 0;
    end
    local lockController = obj:GetController("lock")
    if lockController then
        lockController.selectedIndex = 0;
    end
    local raceController = obj:GetController("topicon")
    if raceController then
        raceController.selectedIndex = 0;
    end
    if this.ifShowBar then
        this.ifShowBar.selectedIndex=0
    end
    if isBag then
        if data.itemId == nil or RedDotsBagItemHandler.getFlag(data.itemId) ~= Config.RedDotsFlagState.Needful then
            this.isShowRedDot.selectedIndex = 0;
        else
            this.isShowRedDot.selectedIndex = 1;
        end
        this.itemLimit = obj:GetChild("num2");
        this.itemBar = obj:GetChild("bar");
        local limit = 0;
        if tonumber(data["scriptId"]) == EnumConst.EnuItem.RAND_AWARD then
            --随机型宝箱
            limit = decodeJsonStrToTabel(data["itemFunction"])[4];
        elseif tonumber(data["scriptId"]) == EnumConst.EnuItem.FIX_AWARD then
            --固定型宝箱
            limit = decodeJsonStrToTabel(data["itemFunction"])[2];
        end
        if this.ifShowBar then
            if limit > 0 then
                this.ifShowBar.selectedIndex = 1;
                this.itemLimit.text = limit;
                this.itemBar.value = math.min(tonumber(data["num"]) / limit * 100, 100);
            end
        end
    end
    if data ~= nil then
        local constData = ItemManager.getItemConstDatabyModelId(data.itemModelId)
        local curIcon = img_Icon
        if constData.itemType == 9 then
            soulCtrl.selectedIndex = math.max(1, math.floor(constData.quality / 2));
            curIcon = this.soulIcon
        end
        UIComponentInterface:SetItemAllById(curIcon, img_Quality, img_Frame, data.itemModelId)
        if constData and constData.itemType == EnumConst.ItemTypeEnum.Title then
            img_Icon.url = EnumConst.AtlasPath.ICONAtlas .. constData.icon
            --ctrlMirror.selectedIndex = 1
        end
        if txt_num then
            if data["num"] ~= nil and data["num"] ~= "" then
                data["num"] = tonumber(tostring(data["num"]));
                if logicMgr.ItemManager.IsEquip(data.itemModelId) then
                    if tonumber(data["num"]) == 1 then
                        txt_num.text = "";
                    else
                        txt_num.text = getNumString(tonumber(data["num"]));
                    end
                elseif data["itemType"] ~= nil and tonumber(data["itemType"]) == 10 then
                    if tonumber(data["num"]) == 1 then
                        txt_num.text = "";
                    else
                        txt_num.text = getNumString(tonumber(data["num"]));
                    end
                elseif data["itemType"] ~= nil and tonumber(data["itemType"]) == 256 then
                    ctrl_time_box.selectedIndex = 1;
                    local time_box_text = obj:GetChild("time-box");
                    local strTime;
                    if tonumber(data["num"]) < 0 then
                        strTime = getLanguage("ActivityDesc1050108");
                    else
                        strTime = string.format(getLanguage("Sys_Time_Hour"),data["num"])
                    end
                    if data["isShowBigNum"] then
                        time_box_text.text = "[size=32]"..strTime.."[/size]";
                    else
                        time_box_text.text = strTime;
                    end
                    txt_num.text = "";
                else
                    txt_num.text = getNumString(tonumber(data["num"]));
                end
            else
                txt_num.text = "";
            end
        end
        if constData and constData.icon and constData.itemType == EnumConst.ItemTypeEnum.Hero then
            img_Icon.url = EnumConst.AtlasPath.ICONAtlas .. constData.icon
            if ctrlMirror then
                ctrlMirror.selectedIndex = 1
            end
            local heroId=tonumber(data.itemModelId)%600000
            local notHave=logicMgr.HeroManager.NotHaveByModeId(heroId)
            if isBag and this.ifShowBar and notHave then
                this.ifShowBar.selectedIndex = 1;

                local need=G.dataTable["t_hero"][tostring(heroId)].f_ActiveCount
                this.itemLimit.text = need
                --if tonumber(data.num)<need then
                --    txt_num.text=getNumString(tonumber(data["num"]))
                --else
                --    txt_num.text ="[color=#00FF00]" ..getNumString(tonumber(data["num"])).. "[/color]"
                --end
                this.itemBar.value = math.min(tonumber(data["num"]) / need * 100, 100);
            end
        else
            if ctrlMirror then
                ctrlMirror.selectedIndex = 0
            end
        end
        if constData and constData.cornerMark ~= "" then
            if cornerMarkController then
                cornerMarkController.selectedIndex = 1;
            end
            if cornerMark then
                cornerMark.url = EnumConst.AtlasPath.ICONAtlas .. constData.cornerMark;
            end
        end
        if constData and constData.cornerMarkRight and constData.cornerMarkRight ~= "" then
            if IsDoubleController then
                IsDoubleController.selectedIndex = 1
            end
            if iconDouble then
                iconDouble.url = EnumConst.AtlasPath.ICONAtlas .. constData.cornerMarkRight;
            end
        end
        if ctrlSuit then
            if logicMgr.ItemManager.IsEquip(data.itemModelId) then
                local cfg = dataTable.getDataTableByStringId("t_equip",data.itemModelId)
                ctrlSuit.selectedIndex = cfg.f_EquipSuit
                --iconSuit.url = EnumConst.AtlasPath.ICONAtlas..cfg.f_EquipSuitlcon
            else
                ctrlSuit.selectedIndex = 0
            end
        end
        if stateCtrl then
            if data["state"] ~= nil and data["state"] then
                stateCtrl.selectedPage = "select";
            else
                stateCtrl.selectedPage = "noSelect";
            end
        end
        if txt_Level then
            if data["level"] ~= nil and tonumber(data["level"]) > 0 then
                -- txt_Level.text = "Lv" .. tostring(data["level"]);
                txt_Level.text = string.format(getLanguage("Level"), data.level)
            else
                txt_Level.text = "";
            end
            if data.itemType == EnumConst.ItemTypeEnum.Rune then
                txt_Level.text = "";
            end
        end

        if txt_refine then
            local refine = tonumber(data["curRfLevel"])
            if refine ~= nil and refine > 0 then
                txt_refine.text = "+" .. data["curRfLevel"];
                --if ctrlRefineLevel then
               --     ctrlRefineLevel.selectedIndex = refine
                --end
            else
                txt_refine.text = "";
                --if ctrlRefineLevel then
                --    ctrlRefineLevel.selectedIndex = 0
                --end
            end
            if data.itemType == EnumConst.ItemTypeEnum.Rune then
                if data["level"] and data["level"] > 0 then
                    txt_refine.text = "+" .. data["level"];
                end
            end
        end
        --if ctrlRefineSlot then
        --    ctrlRefineSlot.selectedIndex = logicMgr.EquipManager.GetMaxRefineLevel(data.itemModelId)
        --end
        if this.showNameController then
            if data["isShowName"] then
                this.showNameController.selectedIndex = 1;
                this.name.text = data["name"];
            else
                this.showNameController.selectedIndex = 0;
            end
        end
        if fontController then
            if data["isShowBigNum"] then
                fontController.selectedIndex = 1;
            else
                fontController.selectedIndex = 0;
            end
        end
        if lockController and data["isLock"] then
            lockController.selectedIndex = 1;
        end
        --邮件是否领取奖励，领取后不能点击
        if this.maskCtrl and this.dialogCtrl then
            if data["mailGet"] ~= nil and data["mailGet"] == 0 then
                this.maskCtrl.selectedPage = "noMask";
                this.dialogCtrl.selectedPage = "noDialog";
            elseif data["mailGet"] ~= nil and data["mailGet"] == 1 then
                this.maskCtrl.selectedPage = "mask";
                this.dialogCtrl.selectedPage = "dialog";
            end
        end

        if this.invasionUpCtrl then
            if data["isInvasionUp"] then
                this.invasionUpCtrl.selectedIndex = 1;
            else
                this.invasionUpCtrl.selectedIndex = 0;
            end
        end

        if data.itemType ~= EnumConst.ItemTypeEnum.Fragment then
            local debris = obj:GetController("debris")
            if debris then
                debris.selectedIndex = 0
            end
        end

        obj.onClick:Clear();
        if not notAddClick then
            local heroId = nil
            if data.itemType == EnumConst.ItemTypeEnum.HeroEntity then
                for k,v in pairs(G.dataTable["t_drop"]) do
                    if tonumber(data.itemModelId) == tonumber(v.f_DropPoolId) then
                        heroId = decodeJsonStrToTabel(v.f_Hero);
                        if heroId ~= nil then
                            if raceController then
                                raceController.selectedIndex = logicMgr.HeroManager.GetHeroFactionType(heroId[1][1])
                                --if G.dataTable["t_hero"][tostring(heroId[1][1])].f_HeroRace == 1 then
                                --    raceController.selectedIndex = 1
                                --elseif G.dataTable["t_hero"][tostring(heroId[1][1])].f_HeroRace == 2 then
                                --    raceController.selectedIndex = 2
                                --end
                            end
                        end
                    end
                end
            end
            obj.onClick:Add(function()
                if not notShow then
                    if data.itemType == EnumConst.ItemTypeEnum.HeroEntity then
                        if heroId ~= nil then
                            showUI(PanelNames.UIDrawAnimation, {heroId[1][1], heroId[1][2]}, nil, false, function()
                                closeUI(PanelNames.UIDrawAnimation);
                            end, nil, true, true);
                        end
                        return
                    end
                    if isBag and data.itemType == EnumConst.ItemTypeEnum.TimeBox then
                        logicMgr.UIShowManager.ShowTimeBoxQuickOpenInBag(data.itemId)
                        return
                    end
                    if data["itemModelId"] == nil then
                        return
                    end
                    if logicMgr.ItemManager.IsEquip(data["itemModelId"]) then
                        showUI(PanelNames.UIEquipInfo, nil, data, type);
                    elseif data.itemType == EnumConst.ItemTypeEnum.Fragment then
                        if data.itemId then
                            showUI(PanelNames.UIDebrisInfo, data, EnumConst.DebrisInfoType.Bag)
                        else
                            showUI(PanelNames.UIDebrisInfo, data, EnumConst.DebrisInfoType.View)
                        end
                    elseif data.itemType == EnumConst.ItemTypeEnum.Rune then
                        showUI(PanelNames.UIRuneInfo,data,true)
                    else
                        showUI(PanelNames.UIBagItemInfo, data, type,partnerId, isBag);
                    end
                end
            end);
        end
        if this.ifMultipleCtrl then
            if isMultiple then
                this.ifMultipleCtrl.selectedIndex = 1
            else
                this.ifMultipleCtrl.selectedIndex = 0
            end
        end

        --logicMgr.ItemManager.ReturnToPool(constData)
        local cfg = dataTable.getDataTableByStringId("t_item",data.itemModelId)
        if cfg and cfg.f_ScriptId==300004 and cfg.f_ItemFunction~=nil then
            this.InitTimeItem(obj,cfg)
        end
    end
end
function Item.InitTimeItem(obj,cfg)
    local ctrl_time_box = obj:GetController("time-box")
    local time_box_text = obj:GetChild("time-box")
    ctrl_time_box.selectedIndex = 1
    time_box_text.text = string.format(getLanguage("Sys_Time_Hour"),cfg.f_ItemFunction[2]/60)
end
function Item.DisableClick(obj)
    obj.onClick:Clear();
end
function Item.SetShowRed(idx)
    this.isShowRedDot.selectedIndex = idx
end
--时光宝箱时间显示
function Item.ShowBoxTime(obj,itemModelId)
    local ctrl_time_box = obj:GetController("time-box")
    local time_box_text = obj:GetChild("time-box")
    if not ctrl_time_box then return end
    local cfg = dataTable.getDataTableByStringId("t_item",itemModelId)
    if cfg and cfg.f_BagType == EnumConst.ItemTypeEnum.TimeBox then
        local itemFunction = decodeJsonStrToTabel(cfg.f_ItemFunction)
        ctrl_time_box.selectedIndex = 1
        time_box_text.text = string.format(getLanguage("Sys_Time_Hour"),itemFunction[2]/3600)
    end
end
function Item.setSelectChooseState(obj, selectState, chooseState)
    local selectCtrl = obj:GetController("select");
    local chooseCtrl = obj:GetController("choose");
    if selectState then
        selectCtrl.selectedPage = "select";
    else
        selectCtrl.selectedPage = "noSelect";
    end
    if chooseState then
        chooseCtrl.selectedPage = "choose";
    else
        chooseCtrl.selectedPage = "noChoose";
    end
end

function Item.setNum(go, numtext)
    local obj = go:GetChild("num");
    obj.text = numtext;
end

return Item;